<?php

namespace App\Http\Resources;

use App\Models\CardType;
use App\Models\UserCard;
use App\Models\UserRole;
use Illuminate\Http\Resources\Json\JsonResource;

class UsersResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
     */
    public function toArray($request)
    {
        $cardmodel=UserCard::query()->where('user_id', $this->id)->first();
        if(!is_null($cardmodel)){
            $card_effective_time=CardType::query()->where('id', $cardmodel->card_id)->value('effective_time');
            $vipDurationInSeconds=$card_effective_time*24*60*60;
            $vipEndTime = is_null($cardmodel) ? null : $cardmodel->created_at->addSeconds($vipDurationInSeconds);
        }
        return [
            'id'=>$this->id,
            'username'=>$this->username,
            'phone'=>$this->phone,
            'email'=>$this->email,
            'avatar'=>$this->avatar,
            'avatar_origin'=>$this->when(!empty($this->avatar_origin),$this->avatar_origin),
            'role_id'=>$this->role_id,
            'role_name'=>UserRole::query()->where('id',$this->role_id)->value('name'),
            'is_vip'=>$this->when(!is_null($cardmodel),1,0),
            'card_name'=>$this->when(!is_null($cardmodel),function ()use($cardmodel){
                if(!is_null($cardmodel)){
                    $card_name=CardType::query()->where('id', $cardmodel->card_id)->value('name');
                    return $card_name;
                }else{
                    return null;
                }
            },null),
            'vip_end_time'=>$this->when(!is_null($cardmodel),is_null($cardmodel) ? null : (string)($cardmodel->created_at->addSeconds($vipDurationInSeconds)),null),
            'created_at'=>(string)$this->created_at,
            'updated_at'=>(string)$this->updated_at,
        ];
    }
}
